package com.fla.puzzle;

import java.io.IOException;

import com.fla.puzzle.ui.game.GameModel;
import com.fla.puzzle.utils.SerializationUtils;

import android.content.SharedPreferences;
import android.util.Log;

/**
 * Responsible for saving and restoring {@link GameModel} from local data storage
 */
public class GameModelManager {
    private static final String LOG_TAG = GameModelManager.class.getName();
    
    private static final String SAVED_GAME_KEY = "SAVED_GAME_KEY";
    
    private SharedPreferences preferences;

    public GameModelManager(SharedPreferences preferences) {
        super();
        this.preferences = preferences;
    }

    /**
     * Saves the given game
     * 
     * @param gameModel {@link GameModel}
     */
    public void saveGame(GameModel gameModel) {
        try {
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString(SAVED_GAME_KEY, SerializationUtils.serializeToString(gameModel));
            editor.commit();

            Log.d(LOG_TAG, "Game saved successfully");
        }
        catch (IOException e) {
            Log.e(LOG_TAG, "Cannot serialize object: " + gameModel, e);
        }
    }

    /**
     * Tests if any game was previously saved and can be restored
     * 
     * @return boolean true if saved game exist
     */
    public boolean savedGameExist() {
        return preferences.contains(SAVED_GAME_KEY);
    }

    /**
     * Restores previously saved game and returns it. Returns null if some errors occured during desserialazing
     * 
     * @return {@link GameModel}
     */
    public GameModel restoreGame() {
        String savedGameString = preferences.getString(SAVED_GAME_KEY, null);

        GameModel result = null;
        try {
            result = (GameModel) SerializationUtils.deserializeFromString(savedGameString);
            Log.d(LOG_TAG, "Saved game deserialized: " + result);
        }
        catch (Exception e) {
            Log.e(LOG_TAG, "Cannot deserialize string", e);
        }

        return result;
    }

    /**
     * Removes previously saved game
     */
    public void removeSavedGame() {
        preferences.edit().remove(SAVED_GAME_KEY).commit();

        Log.d(LOG_TAG, "Saved game removed");
    }
}
